package com.niit.session21;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

import com.niit.session20.JDBCUtils;

public class Login {
	
	public static void main(String[] args) {
		Login login = new Login();
//		从键盘录入用户名和密码
		Scanner sc = new Scanner(System.in);
		login.login(sc.nextLine(), sc.nextLine());
		
	}
	
	public void login(String username,String password) {
		Connection conn = JDBCUtils.getConn();
		try {
//			使用字符串拼接SQL语句会导致SQL注入风险
//			Statement statement = conn.createStatement();
//			String sql ="SELECT * FROM user where username = '"+username+"' and password = '"+password+"';";
//			JDBC提供了PreparedStatement来帮助解决SQL注入的风险
//			PreparedStatement通过问号?占位符来替代参数，在内部做了无害化处理，防止SQL注入
			PreparedStatement ps = conn.prepareStatement("SELECT * FROM user where username = ? and password = ?");
			ps.setString(1, username);
			ps.setString(2, password);
//			打印拼接出来的SQL语句
			System.out.println(ps.toString());
			ResultSet rs = ps.executeQuery();
			if(rs.next()) {
				System.out.println("登录成功");
			}else {
				System.out.println("登录失败");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

}
